const crypto = require('crypto')

/**
 * {
  signature: 'de35b6e833c0f46344153ca81359fe4e60bc18c2',
  echostr: '8832705369850821739',
  timestamp: '1722072169',
  nonce: '120354812'
  }
 */
function checkSignature(req, res, next) {
  //定义Token
  const token = "weixin"

  //获取微信发送过来的信息
  const { signature, echostr, timestamp, nonce } = req.query

  //1）将token，timestamp，nonce三个参数进行字典排序，并拼接成一个字符串
  const temStr = [token, timestamp, nonce].sort().join('')

  // 2）进行sha1加密
  const mySignature = crypto.createHash('sha1').update(temStr).digest('hex')

  // 3）开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
  if (mySignature === signature) {
    res.send(echostr)
  } else {
    res.send('error')
  }
}

module.exports = checkSignature